package com.slm.report.ui.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.raizlabs.android.dbflow.structure.database.transaction.QueryTransaction;
import com.slm.mylibrary.base.BaseFragment;
import com.slm.report.databinding.FragmentReportBinding;
import com.slm.report.db.DuShuInfoBean;
import com.slm.report.db.DuShuInfoBean_Table;
import com.slm.report.db.StudentInfoBean;
import com.slm.report.db.VisionDataInfo;
import com.slm.report.db.VisionDataInfo_Table;
import com.slm.report.state.StudentInfoViewModel;

import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: My Application
 * @Package: com.slm.report.ui.fragment
 * @ClassName: ReportFragment
 * @Description: java类作用描述
 * @Author: 王丹丹
 * @CreateDate: 2020/5/30 21:25
 * @UpdateUser: 更新者
 * @UpdateDate: 2020/5/30 21:25
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class ReportFragment extends BaseFragment<StudentInfoViewModel> {

    private FragmentReportBinding viewBinding;
    private StudentInfoBean studentInfoBean;
    private List<VisionDataInfo> visionDataInfos = new ArrayList<>();
    private List<DuShuInfoBean> duShuInfoBeans = new ArrayList<>();
    private List<String> xValues = new ArrayList<>();
    private List<String> duXValues = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        viewBinding = FragmentReportBinding.inflate(LayoutInflater.from(getContext()));
        mViewModel.studentInfoBean.observe(this, new Observer<StudentInfoBean>() {
            @Override
            public void onChanged(StudentInfoBean infoBean) {
                studentInfoBean = infoBean;
                obtainData();
            }
        });
        mViewModel.isChangeVision.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                SQLite.select()
                        .from(VisionDataInfo.class)
                        .where(VisionDataInfo_Table.studentId.eq(studentInfoBean.getId()))
                        .async().queryListResultCallback(new QueryTransaction.QueryResultListCallback<VisionDataInfo>() {
                    @Override
                    public void onListQueryResult(QueryTransaction transaction, @NonNull List<VisionDataInfo> tResult) {
                        visionDataInfos.clear();
                        visionDataInfos.addAll(tResult);
                        viewBinding.slLineChar.clear();
                        drawLineVisionView();
                    }
                }).execute();


            }
        });
        mViewModel.isChangeDu.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                SQLite.select()
                        .from(DuShuInfoBean.class)
                        .where(DuShuInfoBean_Table.studentId.eq(studentInfoBean.getId()))
                        .async()
                        .queryListResultCallback(new QueryTransaction.QueryResultListCallback<DuShuInfoBean>() {
                            @Override
                            public void onListQueryResult(QueryTransaction transaction, @NonNull List<DuShuInfoBean> tResult) {
                                duShuInfoBeans.clear();
                                duShuInfoBeans.addAll(tResult);
                                viewBinding.sphLineChar.clear();
                                viewBinding.cylLineChar.clear();
                                drawDuLine();
                            }
                        })
                        .execute();

            }
        });
        setLineOps(viewBinding.slLineChar);

        setLineOps(viewBinding.sphLineChar);
        setLineOps(viewBinding.cylLineChar);
        return viewBinding.getRoot();
    }

    private void setLineOps(LineChart lineChart) {
        lineChart.getDescription().setEnabled(false);
        lineChart.setDrawGridBackground(false);
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setDrawGridLines(false);
        xAxis.setDrawAxisLine(true);
        //    xAxis.setLabelCount(4,true);
        xAxis.setAxisMinimum(0f);

        xAxis.setGranularity(1);

    }

    private void obtainData() {
        SQLite.select()
                .from(VisionDataInfo.class)
                .where(VisionDataInfo_Table.studentId.eq(studentInfoBean.getId()))
                .async()
                .queryListResultCallback(new QueryTransaction.QueryResultListCallback<VisionDataInfo>() {
                    @Override
                    public void onListQueryResult(QueryTransaction transaction, @NonNull List<VisionDataInfo> tResult) {
                        visionDataInfos.clear();
                        visionDataInfos.addAll(tResult);
                        drawLineVisionView();
                    }
                }).execute();

        SQLite.select()
                .from(DuShuInfoBean.class)
                .where(DuShuInfoBean_Table.studentId.eq(studentInfoBean.getId()))
                .async()
                .queryListResultCallback(new QueryTransaction.QueryResultListCallback<DuShuInfoBean>() {
                    @Override
                    public void onListQueryResult(QueryTransaction transaction, @NonNull List<DuShuInfoBean> tResult) {
                        duShuInfoBeans.clear();
                        duShuInfoBeans.addAll(tResult);
                        drawDuLine();
                    }
                }).execute();

    }

    private void drawLineVisionView() {
        xValues.clear();
        if (ObjectUtils.isNotEmpty(visionDataInfos)) {
            ArrayList<Entry> leftValues = new ArrayList<>();
            ArrayList<Entry> rightValues = new ArrayList<>();
            float minValue = 0;
            float maxValue = 0;

            for (int i = 0; i < visionDataInfos.size(); i++) {
                VisionDataInfo dataInfo = visionDataInfos.get(i);
                xValues.add(TimeUtils.millis2String(dataInfo.getCreateTime(), TimeUtils.getSafeDateFormat("yyyy-M-d")));
                if (StringUtils.isEmpty(dataInfo.getLuoLeftVal())) {
                    if (i == 0) {
                        leftValues.add(new Entry(i, 0));
                    } else {
                        leftValues.add(leftValues.get(i - 1));
                    }
                } else {
                    float value = Float.parseFloat(dataInfo.getLuoLeftVal());
                    if (value < minValue) {
                        minValue = value;
                    } else if (value > maxValue) {
                        maxValue = value;
                    }
                    leftValues.add(new Entry(i, value));
                }

                if (StringUtils.isEmpty(dataInfo.getLuoRightVal())) {
                    if (i == 0) {
                        rightValues.add(new Entry(i, 0));
                    } else {
                        rightValues.add(rightValues.get(i - 1));
                    }
                } else {
                    float value = Float.parseFloat(dataInfo.getLuoRightVal());
                    if (value < minValue) {
                        minValue = value;
                    } else if (value > maxValue) {
                        maxValue = value;
                    }
                    rightValues.add(new Entry(i, value));
                }
            }
            generateDataLine(leftValues, rightValues, viewBinding.slLineChar, maxValue, minValue);
            viewBinding.slLineChar.getXAxis().setAxisMaximum(xValues.size() - 1);
            viewBinding.slLineChar.setVisibleXRange(0, 5);
            viewBinding.slLineChar.getXAxis().setValueFormatter(new ValueFormatter() {
                @Override
                public String getAxisLabel(float value, AxisBase axis) {
                    if (value < 0 || value > xValues.size() - 1) {
                        return "";
                    } else {
                        return xValues.get((int) value);
                    }

                }
            });
            viewBinding.slLl.setVisibility(View.VISIBLE);
        } else {
            viewBinding.slLl.setVisibility(View.GONE);
        }


    }

    private void drawDuLine() {
        duXValues.clear();
        if (ObjectUtils.isNotEmpty(duShuInfoBeans)) {
            ArrayList<Entry> sphLeftValues = new ArrayList<>();
            ArrayList<Entry> sphRightValues = new ArrayList<>();
            ArrayList<Entry> cylLeftValues = new ArrayList<>();
            ArrayList<Entry> cylRightValues = new ArrayList<>();
            float sphMinValue = 0;
            float sphMaxValue = 0;
            float cylMinValue = 0;
            float cylMaxValue = 0;
            for (int i = 0; i < duShuInfoBeans.size(); i++) {
                DuShuInfoBean dataInfo = duShuInfoBeans.get(i);
                duXValues.add(TimeUtils.millis2String(dataInfo.getCreateTime(), TimeUtils.getSafeDateFormat("yyyy-M-d")));
                if (StringUtils.isEmpty(dataInfo.getLeftSph())) {
                    if (i == 0) {
                        sphLeftValues.add(new Entry(i, 0));
                    } else {
                        sphLeftValues.add(sphLeftValues.get(i - 1));
                    }
                } else {
                    float value = Float.parseFloat(dataInfo.getLeftSph());
                    if (value < sphMinValue) {
                        sphMinValue = value;
                    } else if (value > sphMaxValue) {
                        sphMaxValue = value;
                    }
                    sphLeftValues.add(new Entry(i, value));
                }

                if (StringUtils.isEmpty(dataInfo.getRightSph())) {
                    if (i == 0) {
                        sphRightValues.add(new Entry(i, 0));
                    } else {
                        sphRightValues.add(sphRightValues.get(i - 1));
                    }
                } else {
                    float value = Float.parseFloat(dataInfo.getRightSph());
                    if (value < sphMinValue) {
                        sphMinValue = value;
                    } else if (value > sphMaxValue) {
                        sphMaxValue = value;
                    }
                    sphRightValues.add(new Entry(i, value));
                }

                if (StringUtils.isEmpty(dataInfo.getLeftCyl())) {
                    if (i == 0) {
                        cylLeftValues.add(new Entry(i, 0));
                    } else {
                        cylLeftValues.add(cylLeftValues.get(i - 1));
                    }
                } else {
                    float value = Float.parseFloat(dataInfo.getLeftCyl());
                    if (value < sphMinValue) {
                        cylMinValue = value;
                    } else if (value > sphMaxValue) {
                        cylMaxValue = value;
                    }
                    cylLeftValues.add(new Entry(i, value));
                }

                if (StringUtils.isEmpty(dataInfo.getRightCyl())) {
                    if (i == 0) {
                        cylRightValues.add(new Entry(i, 0));
                    } else {
                        cylRightValues.add(cylRightValues.get(i - 1));
                    }
                } else {
                    float value = Float.parseFloat(dataInfo.getRightCyl());
                    if (value < cylMinValue) {
                        cylMinValue = value;
                    } else if (value > cylMaxValue) {
                        cylMaxValue = value;
                    }
                    cylRightValues.add(new Entry(i, value));
                }
            }
            generateDataLine(sphLeftValues, sphRightValues, viewBinding.sphLineChar, sphMaxValue, sphMinValue);
            viewBinding.sphLineChar.getXAxis().setAxisMaximum(duXValues.size() - 1);
            viewBinding.sphLineChar.setVisibleXRange(0, 5);
            viewBinding.sphLineChar.getXAxis().setValueFormatter(new ValueFormatter() {
                @Override
                public String getAxisLabel(float value, AxisBase axis) {
                    if (value < 0 || value > duXValues.size() - 1) {
                        return "";
                    } else {
                        return duXValues.get((int) value);
                    }

                }
            });
            generateDataLine(cylLeftValues, cylRightValues, viewBinding.cylLineChar, cylMaxValue, cylMinValue);
            viewBinding.cylLineChar.getXAxis().setAxisMaximum(duXValues.size() - 1);
            viewBinding.cylLineChar.setVisibleXRange(0, 5);
            viewBinding.cylLineChar.getXAxis().setValueFormatter(new ValueFormatter() {
                @Override
                public String getAxisLabel(float value, AxisBase axis) {
                    if (value < 0 || value > duXValues.size() - 1) {
                        return "";
                    } else {
                        return duXValues.get((int) value);
                    }

                }
            });
            viewBinding.duLl.setVisibility(View.VISIBLE);
        } else {
            viewBinding.duLl.setVisibility(View.GONE);
        }

    }

    /**
     * generates a random ChartData object with just one DataSet
     *
     * @return Line data
     */
    private void generateDataLine(List<Entry> leftValues, List<Entry> rightValue, LineChart lineChart, float maxValue, float minValue) {

        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setLabelCount(5, false);
        leftAxis.setAxisMinimum(minValue - 2);
        leftAxis.setAxisMaximum(maxValue + 2);
        YAxis rightAxis = lineChart.getAxisRight();
        rightAxis.setLabelCount(5, false);
        // rightAxis.setDrawGridLines(false);
        rightAxis.setAxisMinimum(minValue - 2);
        rightAxis.setAxisMaximum(maxValue + 2);

        LineDataSet d1 = new LineDataSet(leftValues, "左眼（L）");
        d1.setLineWidth(2.5f);
        d1.setCircleRadius(4.5f);
        d1.setHighLightColor(Color.rgb(244, 117, 117));
        d1.setCircleColor(ColorTemplate.VORDIPLOM_COLORS[2]);
        d1.setColor(ColorTemplate.VORDIPLOM_COLORS[2]);
        d1.setDrawValues(true);

        LineDataSet d2 = new LineDataSet(rightValue, "右眼（R）");
        d2.setLineWidth(2.5f);
        d2.setCircleRadius(4.5f);
        d2.setHighLightColor(Color.rgb(244, 117, 117));
        d2.setColor(Color.argb(170, 140, 234, 255));
        d2.setCircleColor(Color.argb(170, 140, 234, 255));
        d2.setDrawValues(true);

        ArrayList<ILineDataSet> sets = new ArrayList<>();
        sets.add(d1);
        sets.add(d2);

        lineChart.setData(new LineData(sets));
        lineChart.animateX(750);


    }


}
